<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="合同编号" prop="contractNo">
        <el-input
          v-model="queryParams.contractNo"
          placeholder="请输入合同编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入客户姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入手机号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="购买学科" prop="subject">
        <el-select v-model="queryParams.subject" placeholder="请输入购买学科" clearable
                   @keyup.enter.native="handleChangeSubject"
                   @change="handleChangeSubject">
          <el-option v-for="dict in dict.type.course_subject"
                     :label="dict.label"
                     :value="dict.value"
                     :key="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="购买课程" prop="courseId">
        <el-select v-model="queryParams.courseId" placeholder="请输入意向课程" clearable>
          <el-option v-for="item in courseOptions" :label="item.name" :value="item.id"
                     :key="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="创建日期" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          type="date"
          placeholder="选择日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['crm:contract:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['crm:contract:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['crm:contract:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['crm:contract:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="contractList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <!--      <el-table-column label="合同id" align="center" prop="id"/>-->
      <!--      <el-table-column label="邮箱地址" align="center" prop="email"/>-->
      <el-table-column label="合同编号" align="center" prop="contractNo"/>
      <el-table-column label="客户姓名" align="center" prop="name"/>
      <el-table-column label="手机号" align="center" prop="phone"/>
      <el-table-column label="购买学科" align="center" prop="subject" :formatter="subjectFormatter"/>
      <el-table-column label="购买课程" align="center" prop="courseId" :formatter="courseIdFormatter"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-link size="mini"
                   type="primary"
                   :href="`${baseUrl}${form.fileName}`"
                   :underline="false"
                   target="_blank"
          >
            <i class="el-icon-view"></i>预览
          </el-link>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleView(scope.row)"
            v-hasPermi="['crm:contract:edit']"
          >详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改合同对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号"/>
        </el-form-item>
        <el-form-item label="合同编号" prop="contractNo">
          <el-input v-model="form.contractNo" placeholder="请输入合同编号"/>
        </el-form-item>
        <el-form-item label="客户姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入客户姓名"/>
        </el-form-item>
        <el-form-item label="邮箱地址" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱地址"/>
        </el-form-item>
        <el-form-item label="意向学科" prop="subject">
          <el-input v-model="form.subject" placeholder="请输入意向学科"/>
        </el-form-item>
        <el-form-item label="活动id" prop="activityId">
          <el-input v-model="form.activityId" placeholder="请输入活动id"/>
        </el-form-item>
        <el-form-item label="活动名称" prop="activityName">
          <el-input v-model="form.activityName" placeholder="请输入活动名称"/>
        </el-form-item>
        <el-form-item label="课程id" prop="courseId">
          <el-input v-model="form.courseId" placeholder="请输入课程id"/>
        </el-form-item>
        <el-form-item label="课程名称" prop="courseName">
          <el-input v-model="form.courseName" placeholder="请输入课程名称"/>
        </el-form-item>
        <el-form-item label="渠道" prop="channel">
          <el-input v-model="form.channel" placeholder="请输入渠道"/>
        </el-form-item>
        <el-form-item label="部门ID" prop="deptId">
          <el-input v-model="form.deptId" placeholder="请输入部门ID"/>
        </el-form-item>
        <el-form-item label="文件名称" prop="fileName">
          <el-input v-model="form.fileName" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="订单价格" prop="contractOrder">
          <el-input v-model="form.contractOrder" placeholder="请输入订单价格"/>
        </el-form-item>
        <el-form-item label="课程价格" prop="coursePrice">
          <el-input v-model="form.coursePrice" placeholder="请输入课程价格"/>
        </el-form-item>
        <el-form-item label="${comment}" prop="processInstanceId">
          <el-input v-model="form.processInstanceId" placeholder="请输入${comment}"/>
        </el-form-item>
        <el-form-item label="商机ID" prop="businessId">
          <el-input v-model="form.businessId" placeholder="请输入商机ID"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <contract-details ref="contractDetails"
                      v-if="showContractDetails"
                      :show="showContractDetails"
                      :id="contractId"
                      @input="handleChildInput"
    ></contract-details>
  </div>
</template>

<script>
  import {listContract, getContract, delContract, addContract, updateContract} from "@/api/crm/contract";
  import {listCourse} from "../../../api/crm/course";

  import ContractDetails from "./details";

  export default {
    name: "Contract",
    dicts: ['course_subject',],
    components: {ContractDetails},
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 合同表格数据
        contractList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          phone: null,
          contractNo: null,
          name: null,
          email: null,
          subject: null,
          activityId: null,
          activityName: null,
          courseId: null,
          courseName: null,
          channel: null,
          status: null,
          deptId: null,
          fileName: null,
          contractOrder: null,
          discountType: null,
          coursePrice: null,
          processInstanceId: null,
          businessId: null,
          createTime: null,
        },
        // 日期查询
        themeTime: null,
        // 购买课程
        courseOptions: [],
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          name: [
            {required: true, message: "客户姓名不能为空", trigger: "blur"}
          ],
        },
        baseUrl: process.env.VUE_APP_BASE_API,
        contractId: null,
        showContractDetails: false,
      };
    },
    created() {
      this.getList();
    },
    methods: {
      /** 查询合同列表 */
      getList() {
        this.loading = true;
        listContract(this.queryParams).then(response => {
          this.contractList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          phone: null,
          contractNo: null,
          name: null,
          email: null,
          subject: null,
          activityId: null,
          activityName: null,
          courseId: null,
          courseName: null,
          channel: null,
          status: null,
          createBy: null,
          deptId: null,
          createTime: null,
          fileName: null,
          contractOrder: null,
          discountType: null,
          coursePrice: null,
          processInstanceId: null,
          businessId: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加合同";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getContract(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改合同";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateContract(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addContract(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除合同编号为"' + ids + '"的数据项？').then(function () {
          return delContract(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('crm/contract/export', {
          ...this.queryParams
        }, `contract_${new Date().getTime()}.xlsx`)
      },
      //  搜索显示：购买课程
      handleChangeSubject(value) {
        this.queryParams.courseId = null;
        listCourse({subject: value}).then(resp => {
          this.courseOptions = resp.rows;
        })
      },
      //  页面显示：学科
      subjectFormatter(row) {
        return this.selectDictLabel(this.dict.type.course_subject, row.subject);
      },
      //  页面显示：课程
      courseIdFormatter(row) {
        console.log(row.courseId);
        // listCourse({subject: row.courseId}).then(resp => {
        //   this.courseOptions = resp.row.courseName;
        // })
      },
      //  查看详情
      handleView(row) {
        this.contractId = row.id;
        this.showContractDetails = true;
      },
      handleChildInput() {
        this.showContractDetails = false;
      },
    }
  };
</script>
